# 批量打包脚本 - PowerShell版本

# 自动发现环境配置文件
function Discover-Environments {
    $envFiles = Get-ChildItem -Path "." -Filter ".env.*" | 
        Where-Object { $_.Name -ne ".env.development" } | 
        Sort-Object Name
    
    $environments = @()
    
    foreach ($envFile in $envFiles) {
        $mode = $envFile.Name -replace "\.env\.", ""
        
        try {
            # 读取环境配置文件获取页面标题
            $envContent = Get-Content $envFile.FullName -Raw -Encoding UTF8
            $titleMatch = $envContent -match "VUE_APP_TITLE\s*=\s*(.+)"
            $name = if ($titleMatch) { $matches[1].Trim() } else { $mode }
            
            $environments += @{
                name = $name
                mode = $mode
                outputDir = "dist-$mode"
                envFile = $envFile.Name
            }
        }
        catch {
            Write-Warning "⚠️  无法读取配置文件 $($envFile.Name): $($_.Exception.Message)"
        }
    }
    
    return $environments
}

# 自动发现环境配置
$environments = Discover-Environments

Write-Host "🚀 开始批量打包$($environments.Count)个环境配置..." -ForegroundColor Green
Write-Host ""

if ($environments.Count -eq 0) {
    Write-Host "❌ 未发现任何环境配置文件！" -ForegroundColor Red
    Write-Host "请确保项目根目录下存在 .env.* 格式的配置文件（除了 .env.development）" -ForegroundColor Yellow
    exit 1
}

# 清理旧的dist目录
if (Test-Path "dist") {
    Write-Host "🧹 清理旧的dist目录..." -ForegroundColor Yellow
    Remove-Item -Recurse -Force "dist"
}

# 创建主dist目录
New-Item -ItemType Directory -Path "dist" -Force | Out-Null

$successCount = 0
$failCount = 0

# 逐个打包每个环境
for ($i = 0; $i -lt $environments.Count; $i++) {
    $env = $environments[$i]
    $index = $i + 1
    
    Write-Host "`n📦 [$index/$($environments.Count)] 正在打包 $($env.name) ($($env.mode))..." -ForegroundColor Cyan
    
    try {
        # 设置环境变量并执行打包
        $env:BUILD_OUTPUT_DIR = $env.outputDir
        $env:NODE_ENV = "production"
        
        Write-Host "   执行命令: vue-cli-service build --mode $($env.mode)" -ForegroundColor Gray
        
        # 执行打包命令
        $buildResult = & npm run "build:$($env.name)" 2>&1
        
        if ($LASTEXITCODE -eq 0) {
            # 将打包结果移动到dist目录下的子目录
            $sourceDir = $env.outputDir
            $targetDir = "dist\$($env.mode)"
            
            if (Test-Path $sourceDir) {
                if (Test-Path $targetDir) {
                    Remove-Item -Recurse -Force $targetDir
                }
                Move-Item $sourceDir $targetDir
                Write-Host "   ✅ $($env.name) 打包成功 -> dist/$($env.mode)/" -ForegroundColor Green
                $successCount++
            } else {
                throw "打包输出目录 $sourceDir 不存在"
            }
        } else {
            throw "打包命令执行失败，退出代码: $LASTEXITCODE"
        }
        
    } catch {
        Write-Host "   ❌ $($env.name) 打包失败: $($_.Exception.Message)" -ForegroundColor Red
        $failCount++
    }
}

# 生成打包报告
Write-Host "`n" + "=" * 50
Write-Host "📊 打包完成报告" -ForegroundColor Yellow
Write-Host "=" * 50
Write-Host "✅ 成功: $successCount 个环境" -ForegroundColor Green
Write-Host "❌ 失败: $failCount 个环境" -ForegroundColor Red
Write-Host "📁 输出目录: dist/"

if ($successCount -gt 0) {
    Write-Host "`n📂 生成的目录结构:" -ForegroundColor Cyan
    $distContents = Get-ChildItem "dist" -Directory
    foreach ($dir in $distContents) {
        Write-Host "   dist/$($dir.Name)/" -ForegroundColor White
    }
}

if ($failCount -gt 0) {
    Write-Host "`n⚠️  请检查失败的打包日志并重试" -ForegroundColor Yellow
    exit 1
} else {
    Write-Host "`n🎉 所有环境打包完成！" -ForegroundColor Green
}
